package com.team2.shoppingService;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.util.ArrayList;

import org.codehaus.groovy.ant.FileScanner;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class Util {
	public static String encodeUrl(String raw) {
		return raw.replaceAll(" ", "%20");
	}

	public static String computeHashFromBytes(byte[] bytes) {
		byte[] hashedStream = null;

		int bytesRead;
		try {
			MessageDigest hasher = MessageDigest.getInstance("MD5");
			hasher.update(bytes);
			hashedStream = hasher.digest();

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		String hash = "";

		for (int i = 0; i < hashedStream.length; i++) {
			hash += Integer.toString((hashedStream[i] & 0xff) + 0x100, 16)
					.substring(1);
		}
		return hash;
	}

	public static String loadImage(String url) {
		String pathname = Configuration.CONTEXT+Configuration.TEMPPATH
				+ computeHashFromBytes(url.getBytes()) + ".jpg";
		File file = new File(pathname);
		if (file.exists()) {
			return pathname;
		}
		try {
			HttpURLConnection httpConnection = (HttpURLConnection) new URL(url)
					.openConnection();
			int statusCode = httpConnection.getResponseCode();
			if (statusCode == 200) {
				InputStream content = httpConnection.getInputStream();
				FileOutputStream fos = new FileOutputStream(pathname);
				byte[] buffer = new byte[8000];
				int numberRead = content.read(buffer);
				while (numberRead > 0) {
					fos.write(buffer, 0, numberRead);
					numberRead = content.read(buffer);
				}
				fos.close();
			} else {
				return null;
			}
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		return pathname;
	}

	public static String getRawHttpResponse(String url) {
		System.out.println("requested url\n" + url);
		StringBuilder builder = new StringBuilder();
		try {
			HttpURLConnection httpConnection = (HttpURLConnection) new URL(url)
					.openConnection();
			int statusCode = httpConnection.getResponseCode();
			if (statusCode == 200) {
				InputStream content = httpConnection.getInputStream();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(content));
				String line;
				while ((line = reader.readLine()) != null) {
					builder.append(line);
				}
			} else {

			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return builder.toString();
	}

}
